package com.sinai.mshab.client.ui;

import java.util.HashMap;
import java.util.Iterator;

import com.google.gwt.user.client.rpc.IsSerializable;

/**
 * A Key is a way to uniquely identify an entity in an application (eg.
 * employee, client, record).
 * 
 * A key can have only 1 table name, this table name is the main table
 * containing all the entities (eg. table Clients)
 * 
 * A key can contain several field names and values to uniquely identify an
 * entity, (eg: firstname = 'Bob', lastname = 'Sanders')
 * 
 * Almost all automated components in MSHAB use the Key: FormData needs it to
 * know how to store the data. Also how to retreive the data so that the form
 * can be populated. AdvancedSearch also cannot function without a valid key.
 * 
 * The primary key for the application can be found in FormData. It is advised
 * to set up this key right away in the Entry Point of your application and/or
 * before submitting, populating and searching.
 * 
 * @author Arthur Kalmenson
 */
public class Key implements IsSerializable {

	/**
	 * The list of keys.
	 * 
	 * @gwt.typeArgs <java.lang.String, java.lang.String>
	 */
	HashMap keys = new HashMap();

	/**
	 * The table name associated with this key.
	 */
	String table_name = "";

	/**
	 * Adds <code>key</code> as a key to a database table setting it's value
	 * to null.
	 * 
	 * @param key
	 *            the key to add.
	 */
	public void add(String key) {
		keys.put(key, null);
	}

	/**
	 * Adds <code>key</code> as a key to a database table and setting the
	 * value of that key to <code>value</code>.
	 * 
	 * @param key
	 *            the key to add.
	 * @param value
	 *            the value of the key.
	 * @param the
	 *            table name associated with this key, 1 table name per key
	 */
	public void add(String key, String value, String table) {
		keys.put(key, value);
		table_name = table;
	}

	/**
	 * Returns the value of <code>key</code>.
	 * 
	 * @param key
	 *            the key's whos value is required.
	 */
	public void get(String key) {
		keys.get(key);
	}

	/**
	 * Returns all the keys in this Key <code>Key</code>.
	 * 
	 * @return all the keys in this Key <code>Key</code>.
	 */
	public HashMap getKeys() {
		return keys;
	}

	/**
	 * Returns the table name associated with this Key
	 * 
	 * @return the table name associated with this Key
	 */
	public String getTableName() {
		return table_name;
	}

	/**
	 * Returns true if the Key is empty, false otherwise.
	 * 
	 * @return true if the Key is empty, false otherwise.
	 */
	public boolean isEmpty() {
		return keys.isEmpty();
	}
	
	/**
	 * Returns the where part of the SQL statement
	 * 
	 * @return the where clause of the sql
	 */
	public String toString() {
		String sql_where = " WHERE ";
		Iterator primary_keys = keys.keySet().iterator();
		while (primary_keys.hasNext()) {
			String key = (String) primary_keys.next();
			String val = (String) keys.get(key);
			sql_where += " " + key + "='" + val + "'";
		}
		return sql_where;
	}
}
